package cn.client.ui.view.main.chat.friend

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Divider
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupProperties
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import cn.client.data.remoteData.bean.FriendCardItem
import coil.compose.AsyncImage


/**
 * 好友列表
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FriendListPage(
    navController: NavController,
    onClickFriendInfo: (Int, Int) -> Unit = { _, _ -> },
    onClickFriendApply: (Int) -> Unit = {},
    onClickSearchUser: (Int) -> Unit = {},
    viewModel: FriendViewModel = hiltViewModel(),
) {
    data class DropdownItem(val title: String, val id: Int)

    val dropdownList = listOf(
        DropdownItem("好友申请", 1),
        DropdownItem("查找用户", 2)
    )
    var expanded by remember { mutableStateOf(false) }
    val context = LocalContext.current
    var userId by remember { mutableStateOf(-1) }

    // 初始化时获取数据
    viewModel.dispatch(FriendViewModel.PageIntent.GetUser("获取本地用户缓存"))

    LaunchedEffect(Unit) {
        viewModel.pageEvents.collect { it ->
            when (it) {
                is FriendViewModel.PageEvent.Error -> {
                    Toast.makeText(context, "未查询到数据：${it.error}", Toast.LENGTH_LONG).show()
                }

                is FriendViewModel.PageEvent.UserRes -> {
                    val newUserId = it.uid
                    userId = newUserId
                    Toast.makeText(context, "查询成功！", Toast.LENGTH_LONG).show()
                    viewModel.dispatch(FriendViewModel.PageIntent.FriendList(uid = newUserId))
                }

                is FriendViewModel.PageEvent.GetErr -> {
                    Toast.makeText(context, "错误：${it.msg}", Toast.LENGTH_SHORT).show()
                }

                else -> {}
            }

        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        TopAppBar(
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.primary
            ),
            title = { Text("好友列表") },
            /* 左边按钮 */
            navigationIcon = {
                IconButton(onClick = { navController.navigateUp() }) {
                    Icon(Icons.AutoMirrored.Filled.ArrowBack, null)
                }
            },
            /* 右边按钮（可以是多个） */
            actions = {
                IconButton(onClick = { expanded = !expanded }
                ) { Icon(Icons.Filled.MoreVert, null) }
                /* 下拉框 */
                DropdownMenu(
                    expanded = expanded,
                    onDismissRequest = { expanded = !expanded }, // 当下拉菜单展开/关闭时更新状态
                    modifier = Modifier.wrapContentSize(),
                    properties = PopupProperties(
                        focusable = true,
                        dismissOnBackPress = false,
                        dismissOnClickOutside = true
                    )
                ) {
                    // 在这里遍历 dropdownList 并创建 DropdownMenuItem
                    dropdownList.forEach { dropItem ->
                        DropdownMenuItem(
                            { Text(text = dropItem.title) },
                            onClick = {
                                expanded = false
                                // 根据 dropItem.id 判断并执行页面跳转
                                when (dropItem.id) {
                                    1 -> { /* 跳转到“好友申请”页面 */
                                        onClickFriendApply(userId)
                                    }

                                    2 -> { /* 跳转到“查找用户”页面 */
                                        onClickSearchUser(userId)
                                    }

                                    else -> {
                                        Unit
                                    }
                                }

                            }
                        )
                    }
                }
            }
        )
        /* 使用懒加载列表显示好友item */
        LazyColumn(
            modifier = Modifier.padding(10.dp),
        ) {
            // 观察好友列表状态并遍历渲染每个好友项
            items(viewModel.friendList.value) { friend ->
                FriendItem(
                    friend = friend,
                    avatarClickListener = object : AvatarClickListener {
                        override fun onAvatarClicked(friend: FriendCardItem) {
                            // TODO: 在这里处理好友头像的点击事件
                            onClickFriendInfo(userId, friend.fid)
                        }
                    }
                )
                // 在每个列表项后面添加一个分割线
                Divider(
                    modifier = Modifier.fillMaxWidth(),
                    thickness = 1.dp,
                    color = Color.LightGray
                )
            }
        }
    }

}

/**
 * 回调：用于在头像被点击时通知父可组合项
 */
interface AvatarClickListener {
    fun onAvatarClicked(friend: FriendCardItem)
}

@Composable
fun FriendItem(
    friend: FriendCardItem,
    avatarClickListener: AvatarClickListener,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .height(50.dp)
            .padding(2.dp)
    ) {
        /* 头像 */
        AsyncImage(
            model = friend.avatar,
            contentDescription = "Contact profile picture",
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .size(40.dp)
                .clip(CircleShape)
                .border(1.dp, MaterialTheme.colorScheme.primary, CircleShape)
                .align(Alignment.CenterVertically) // Align the image to the end (right side)
                .clickable {
                    /* 点击事件 */
                    avatarClickListener.onAvatarClicked(friend)
                }
        )
        Spacer(
            modifier = Modifier
                .width(8.dp)
                .fillMaxHeight()
        )
        Column(
            modifier = Modifier.fillMaxHeight()
        ) {
            /* 名称 */
            friend.nickname?.let {
                Text(
                    text = it,
                    color = MaterialTheme.colorScheme.secondary,
                    modifier = modifier
                        .padding(top = 12.dp)
                        .fillMaxWidth(),
                    style = MaterialTheme.typography.titleSmall
                )
            }
        }
    }
}

